package com.yang.servlet;

import com.yang.pojo.Category;
import com.yang.service.CategoryService;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.UUID;

@WebServlet("/CategoryUpdateServlet")
@MultipartConfig
public class CategoryUpdateServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        CategoryService categoryService = new CategoryService();
        int categoryId = Integer.parseInt(request.getParameter("categoryId"));
        String categoryName = request.getParameter("categoryName");
        String CategoryIcon = request.getParameter("oldCategoryIcon");
        Part part = request.getPart("categoryIcon");
        if(part.getSize() > 0){
            //保存分类信息
            //a给图片重新命名
            //拿到这个图片的名字
            String header = part.getHeader("Content-Disposition");
            //找到点这里的索引
            int index1 = header.lastIndexOf(".");
            //拿到双引号位置的索引
            int index2 = header.lastIndexOf("\"");
            //拿到.jpg
            String ext = header.substring(index1,index2);
            //拿到图片的名字
            String iconName = UUID.randomUUID().toString().replace("-","")+ext;
            //b获取categoryImage目录的路径（部署到服务器之后的路径）
            String dir = getServletContext().getRealPath("/categoryImages");
            //c存储图片
            part.write(dir + "/" + iconName);
            //将分类信息保存到数据库
            CategoryIcon = "categoryImages/" + iconName;
        }

        try {
            boolean b = categoryService.updateCategoryById(categoryName, CategoryIcon, categoryId);
            String tips = b?"<label style='color:green'>修改成功</label>":"<label style='color:red'>修改失败</label>";
            ArrayList<Category> category = categoryService.findCategory();
            request.setAttribute("tips",tips);
            request.setAttribute("category",category);
            request.getRequestDispatcher("category_list.jsp").forward(request,response);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
